<template>
  <div class="chat-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="菜包AI助手"
      left-arrow
      @click-left="$router.go(-1)"
      fixed
    />

    <!-- 消息列表区域 -->
    <div class="content-wrapper">
      <div class="message-list">
        <div class="message-item"
          v-for="(message, index) in messages"
          :key="index"
          :class="{ 'message-user': message.isUser }"
        >
          <!-- AI头像 -->
          <div class="avatar" v-if="!message.isUser">
            <img src="@/assets/ai-avatar.png" alt="AI">
          </div>

          <!-- 用户头像 -->
          <div class="avatar" v-if="message.isUser">
            <img src="@/assets/user-avatar.png" alt="用户">
          </div>

          <!-- 消息内容 -->
          <div class="message-content" :class="{ 'user-content': message.isUser }">
            {{ message.content }}
          </div>
        </div>
      </div>

      <!-- 底部固定区域 -->
      <div class="footer">
        <!-- 快捷操作按钮行 -->
        <div class="quick-actions">
          <van-button
            v-for="(action, index) in quickActions"
            :key="index"
            size="small"
            plain
            @click="handleQuickAction(action)"
          >
            {{ action.text }}
          </van-button>
        </div>

        <!-- 输入框区域 -->
        <div class="input-area">
          <van-field
            v-model="inputMessage"
            placeholder="请输入消息"
            :border="false"
            clearable
            @keyup.enter="sendMessage"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                @click="sendMessage"
              >
                发送
              </van-button>
            </template>
          </van-field>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { sendMessage } from '@/api/ai'
export default {
  name: 'AiChat',
  data () {
    return {
      messages: [], // 消息列表
      inputMessage: '', // 输入框内容
      inputType: 'dialogBox', // 请求类型，默认对话框发送，可能是快捷键发送recommend等
      quickActions: [
        { text: '今日推荐', type: 'recommend' },
        { text: '健康咨询', type: 'health' },
        { text: '菜谱推荐', type: 'recipe' },
        { text: '个人信息', type: 'profile' }
      ]
      // firstFlag: true // 是否为第一次进入的每日推荐
    }
  },
  created () {
    // 直接发送欢迎消息
    this.sendWelcomeMessage()
  },
  methods: {
    // 发送欢迎消息
    sendWelcomeMessage () {
      // 直接添加AI消息
      this.messages.push({
        content: '欢迎使用菜包AI助手，以下是今日为您推荐的农产品：',
        isUser: false
      })

      // 模拟AI回复推荐内容
      // setTimeout(() => {
      //   this.messages.push({
      //     content: '1. 应季蔬菜：西红柿、青椒、茄子\n2. 新鲜水果：苹果、橙子、梨\n3. 特色农产：有机大米、土鸡蛋',
      //     isUser: false
      //   })
      // }, 1000)

      // 调用recommend输入类型请求
      this.inputMessage = '自动每日推荐'
      this.inputType = 'recommend'
      this.sendMessage('firstRecommend')
    },

    // 发送消息
    async sendMessage (isAutoRecommend) {
      // 每次发送滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      if (!this.inputMessage || !this.inputMessage.trim()) return

      if (isAutoRecommend !== 'firstRecommend') {
        // 添加用户消息
        this.messages.push({
          content: this.inputMessage,
          isUser: true
        })
      }

      // 如果是获取用户个人病例调用
      if (this.inputType === 'profile') {
        // 跳转个人病例页
        this.$router.push('/medicalrecord')
        // 清空输入框
        this.inputMessage = ''

        // 重置请求类型
        this.inputType = 'dialogBox'

        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })
        return
      }

      // 菜谱推荐禁用
      if (this.inputType === 'recipe') {
        // 清空输入框
        this.inputMessage = ''

        // 重置请求类型
        this.inputType = 'dialogBox'

        setTimeout(() => {
          this.messages.push({
            content: '菜谱推荐功能，小菜包还在学习哦',
            isUser: false
          })
          // 滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }, 1000)
        return
      }

      // TODO: 调用AI接口获取回复
      try {
        // 模拟AI回复
        // setTimeout(() => {
        //   this.messages.push({
        //     content: '这是AI助手的回复',
        //     isUser: false
        //   })
        // }, 1000)
        const { data } = await sendMessage(this.inputMessage, this.inputType)
        if (data) {
          // 每日推荐解析
          if (this.inputType === 'recommend') {
            this.messages.push({
              content: `推荐产品：${data.name}。推荐理由：${data.reason}`,
              isUser: false
            })
          } else {
            // 其他解析-通用解析
            this.messages.push({
              content: data.message,
              isUser: false
            })
          }
        }

        // 调用方法传递对话框内容和请求类型
      } catch (error) {
        console.error('消息发送失败:', error)
      }

      // 清空输入框
      this.inputMessage = ''

      // 重置请求类型
      this.inputType = 'dialogBox'

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    // 处理快捷操作
    handleQuickAction (action) {
      let message = ''
      switch (action.type) {
        case 'recommend':
          message = '请为我推荐今天适合购买的农产品'
          break
        case 'health':
          message = '我想咨询一些健康相关的问题'
          break
        case 'recipe':
          message = '请为我推荐一些适合今天的菜谱'
          break
        case 'profile':
          message = '请告诉我关于我的个人信息'
          break
        default:
          message = action.text
      }
      this.inputMessage = message
      this.inputType = action.type
      this.sendMessage()
    },

    // 滚动到底部
    scrollToBottom () {
      const messageList = document.querySelector('.message-list')
      messageList.scrollTop = messageList.scrollHeight
    }
  }
}
</script>

<style lang="less" scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding-top: 46px;
  background-color: #f7f7f7;
}

.content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  margin-bottom: 160px; /* 为底部区域留出空间 */
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;

  &.message-user {
    flex-direction: row-reverse;
  }
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 10px;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  background-color: #fff;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.5;
  word-break: break-all;

  &.user-content {
    background-color: #95ec69;
  }
}

.footer {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  margin: 0 10px;
  border-radius: 8px;
}

.quick-actions {
  display: flex;
  justify-content: space-around;
  margin-bottom: 8px;

  .van-button {
    margin: 0 5px;
  }
}

.input-area {
  display: flex;
  align-items: center;
  background-color: #f7f7f7;
  border-radius: 4px;
  padding: 3px 5px;

  .van-field {
    flex: 1;
  }

  .van-button {
    margin-left: 10px;
  }
}
</style>
